package com.demo.config.controller;

import com.demo.common.bean.Book;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author: xiaoxiangjie
 * @Description:
 * @Date: 2021/3/21
 */
@RestController
@RequestMapping("/consumer1Controller")
public class Consumer1Controller {


    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getBookInfo")
    @HystrixCommand(fallbackMethod = "getBookInfoError")
    public List getBookInfo(@RequestParam("name") String name) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("name", name);
        ///MICROSERVICE-PROVIDER1
        ResponseEntity<List> forEntity = restTemplate.getForEntity("http://MICROSERVICE-PROVIDER1/provider1Controller/getBookInfo?name={name}", List.class, paramMap);
        //ResponseEntity<List> forEntity = restTemplate.getForEntity("http://localhost:8088/provider1Controller/getBookInfo?name={name}",List.class,paramMap);

        return forEntity.getBody();
    }

    @GetMapping("/getBookInfoBak")
    public List getBookInfoBak(@RequestParam("name") String name) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("name", name);
        ///MICROSERVICE-PROVIDER1
        return restTemplate.getForObject("http://MICROSERVICE-PROVIDER1/provider1Controller/getBookInfo?name={name}", List.class, paramMap);
    }

    @GetMapping("/addBookInfo")
    public String addBookInfo() {
        Book book = new Book();
        book.setName("红楼梦" + new Random().nextInt(20));
        book.setPrice(new BigDecimal(new Random().nextDouble()*100));
        ///MICROSERVICE-PROVIDER1
        return restTemplate.postForObject("http://MICROSERVICE-PROVIDER1/provider1Controller/addBookInfo", book, String.class);
    }


    public List getBookInfoError(String name) {
        System.out.println("服务端error");
        return new ArrayList();
    }

}
